#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <string.h>
#include <syslog.h>
#include <stdlib.h>

#include "log.h"

#define PORTNUM 13000
#define HOSTLEN 256

#define LOG_DIR "./log"

#define oops(msg) {perror(msg); exit(1);}


int main(int argc, char **argv)
{
	struct sockaddr_in addr;
	memset((void*)&addr, 0, sizeof(addr));

	char hostname[HOSTLEN];
	int sock_id, socket_fd;

	time_t now;

	if((sock_id = socket(AF_INET, SOCK_STREAM, 0))==-1)
	{
		write_log(LOG_DEBUG, LOG_DIR, "%s", "create socket error!");
		oops("create socket error!");
	}

	gethostname(hostname, sizeof(hostname));
	
	struct hostent *hp = gethostbyname(hostname);

	if(hp==NULL)
	{
		write_log(LOG_DEBUG, LOG_DIR, "%s", "gethostbyname error!");
		oops("gethostbyname error!");
	}

	memcpy((void*)&addr.sin_addr, (void*)hp->h_addr, hp->h_length);

	addr.sin_port = htons(PORTNUM);
	addr.sin_family = AF_INET;

	if(bind(sock_id, (struct sockaddr*)&addr, sizeof(addr))!=0)
	{
		write_log(LOG_DEBUG, LOG_DIR, "%s", "bind socket error!");
		oops("bind socket error!");
	}

	if(listen(sock_id, 1)!=0)
	{
		write_log(LOG_DEBUG, LOG_DIR, "%s", "socket listen error!");
		oops("listen socket error!");
	}

	while(1)
	{
		if((socket_fd = accept(sock_id, NULL, NULL))==-1)
		{
			write_log(LOG_DEBUG, LOG_DIR, "%s", "accept error!");
			oops("accept error!");
		}

		char sendData[1000] = {0};
		int msgLen;
		int sed = 0;
				
		//while(sed!=msgLen)
		while(1)
		{
			now = time(NULL);
			memset((void*)sendData, 0, 1000);
			sprintf(sendData, "%s:%s \n", "The time is ..", ctime(&now));
			int msgLen = strlen(sendData);

			sed += send(socket_fd, (void*)sendData, msgLen, 0);
			sleep(1);
		}
		close(socket_fd);
	}

	return 0;
}
